/*
 * @Author: xinyang3
 * @Date: 2021-09-03 09:49
 * @Descripttion: fetch 封装
 * @LastEditors: xinyang3
 * @LastEditTime: 2022-04-02 17:22
 */
import $qs from "qs";
import Loading from "../views/components/loading";

function getfetch() {
  const fetch = window.fetch || self.fetch || undefined;

  if (!fetch) {
    return console.warn("browser fetch api is not supported.");
  }
  return fetch;
}
const fetchs = getfetch();
const url_prefiex = `/bgmg`;

const request = {};

const option = {
  cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
  // credentials: "same-origin", // include, same-origin, *omit
  headers: {
    // "user-agent": "Mozilla/4.0 MDN Example",
    "Content-Type": "application/json",
    "self-key": "123",
  },
  method: "get", // *GET, POST, PUT, DELETE, etc.
  mode: "cors", // no-cors, cors, *same-origin
  redirect: "follow", // manual, *follow, error
  referrer: "no-referrer", // *client, no-referrer
};

/**
 * @description: get request
 * @param {*} url
 * @param {*} params
 * @return {*}
 */
request.get = async function (url, params = {}) {
  const { vm } = new Loading({});
  const options = Object.assign({}, option, {});
  url = url_prefiex + url + "?" + $qs.stringify(params);
  const response = await fetchs(url, options);
  const data = await response.json();
  vm.close && vm.close();
  return data;
};
/**
 * @description: post
 * @param {*} url
 * @param {*} data
 * @return {*}
 */
request.post = function (url, data = {}) {
  const options = Object.assign({}, option, {
    method: "post",
    body: JSON.stringify(data),
  });
  url = url_prefiex + url;
  return fetchs(url, options).then((response) => {
    return response.json();
  });
};

export default request;
